//
//  AliOSSManager.m
//  SmartMin
//
//  Created by 裴烨烽 on 16/1/22.
//  Copyright © 2016年 SmartMin. All rights reserved.
//

#import "AliOSSManager.h"

@interface AliOSSManager()

@end

@implementation AliOSSManager

+(instancetype)sharedOssManager{
    static AliOSSManager *_sharedAccountModel = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedAccountModel = [[AliOSSManager alloc] init];
        [_sharedAccountModel aliossManagerWithInit];
    });
    return _sharedAccountModel;
}


#pragma mark - 初始化
-(void)aliossManagerWithInit{
    if (!self.oSSClient){
        id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:ossAccessKey secretKey:ossSecretKey];
        
        OSSClientConfiguration * conf = [OSSClientConfiguration new];
        conf.maxRetryCount = 3;                                     // 网络请求遇到异常失败后的重试次数
        conf.timeoutIntervalForRequest = 30;                        // 网络请求的超时时间
        conf.timeoutIntervalForResource = 24 * 60 * 60;             // 允许资源传输的最长时间
        
        self.oSSClient = [[OSSClient alloc] initWithEndpoint:ossEndpoint credentialProvider:credential clientConfiguration:conf];
    }
}

#pragma mark - 上传文件信息
-(void)uploadFileWithType:(OSSUploadType)type name:(NSString *)objcName obj:(OSSSingleFileModel *)obj block:(void(^)(NSString *fileUrl))block progress:(void(^)(CGFloat progress))progressBlock{
    OSSPutObjectRequest *putRequest = [[OSSPutObjectRequest alloc]init];
    putRequest.bucketName = ossBucketName;
    if (type == OSSUploadTypeImg){
        putRequest.objectKey = [NSString stringWithFormat:@"Image/%@",obj.objcName];
    } else if (type == OSSUploadTypeOther){
        putRequest.objectKey = [NSString stringWithFormat:@"File/%@",obj.objcName];
    }
    
    putRequest.uploadingData = obj.objcData;
    putRequest.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSInteger byte = (long)totalByteSent;
        NSInteger totalByte = (long)totalBytesExpectedToSend;
        CGFloat progress = byte * 1.f / totalByte;
        
        if (progressBlock){
            progressBlock(progress);
        };
    };

    OSSTask *putTask = [[AliOSSManager sharedOssManager].oSSClient putObject:putRequest];
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            if (block){
                block(putRequest.objectKey);
            }
        } else {
            NSLog(@"upload object failed, error: %@" , task.error);
        }
        return nil;
    }];
    [putTask waitUntilFinished];
}




//
//
//#pragma mark  上传 Laungch
//+(void)uploadLaungchFileWithImg:(OSSSingleFileModel *)objc compressionQuality:(CGFloat)compressionQuality andBlock:(void (^)(NSString *fileName))block{
//    OSSPutObjectRequest *putRequest = [[OSSPutObjectRequest alloc]init];
//    putRequest.bucketName = ossBucketName;
//
//    putRequest.objectKey = [NSString stringWithFormat:@"Laungch/%@",objc.objcName];
//
//    UIImage *image = objc.objcImg;
//    NSData *objcData = UIImageJPEGRepresentation(image,compressionQuality);
//    putRequest.uploadingData = objcData;
//
//    putRequest.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
//        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
//    };
//
//    OSSTask *putTask = [[AliOSSManager sharedOssManager].oSSClient putObject:putRequest];
//    [putTask continueWithBlock:^id(OSSTask *task) {
//        if (!task.error) {
//
//        } else {
//            NSLog(@"upload object failed, error: %@" , task.error);
//        }
//        return nil;
//    }];
////    [putTask waitUntilFinished];
//
//    if (block){
//        block(objc.objcName);
//    }
//}
//
//#pragma mark - 上传文件
//-(void)uploadFileWithImgArr:(NSArray<OSSSingleFileModel> *)objcArr uploadType:(ImageUsingType)type compressionRatio:(CGFloat)compressionRatio block:(void(^)(NSArray *fileUrlArr))fileArrBlock{
//    NSMutableArray *fileUrlArr = [NSMutableArray array];
//    dispatch_queue_t queue = dispatch_queue_create("Blur queue", NULL);
//
//    __weak typeof(self)weakSelf = self;
//    dispatch_async(queue, ^{
//        for (int i = 0 ; i < objcArr.count;i++){
//            OSSSingleFileModel *singleModel = [objcArr objectAtIndex:i];
//            [weakSelf uploadFileWithObjctype:type name:singleModel.objcName objImg:singleModel.objcImg block:^(NSString *fileUrl) {
//                if (!weakSelf){
//                    return ;
//                }
//                [fileUrlArr addObject:fileUrl];
//            } progress:^(CGFloat progress) {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [StatusBarManager statusBarHidenWithText:[NSString stringWithFormat:@"正在上传第%li张图片",(long)(i + 1)]];
//                });
//            }];
//        }
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [StatusBarManager statusBarHidenWithText:@"正在提交信息"];
//            if (fileArrBlock){
//                fileArrBlock(fileUrlArr);
//            }
//        });
//    });
//}
//
//
//
//
//#pragma msrk 上传文件
//-(void)uploadFileWithObjctype:(ImageUsingType)type name:(NSString *)objcName objImg:(UIImage *)img block:(void(^)(NSString *fileUrl))block progress:(void(^)(CGFloat progress))progressBlock{
//    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
//
//    put.bucketName = ossBucketName;
//    if (!objcName.length){
//
//        NSInteger x = arc4random() % 1000;
//        put.objectKey = [NSString stringWithFormat:@"%@%@%li.png",[self getFileNameWithType:ImageUsingTypeUserShow],[NSDate getCurrentTimeWithFileName],(long)x];
//    } else {
//        put.objectKey = objcName;
//    }
//    NSData *fileData = UIImageJPEGRepresentation(img,0.7);
//    put.uploadingData = fileData; // 直接上传NSData
//
//    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {    // 上传进度
//        if (totalByteSent == totalBytesExpectedToSend){
//
//        } else {
//            NSInteger totalByteSentInteger = [[NSString stringWithFormat:@"%lld",totalByteSent] integerValue];
//            NSInteger totalBytesExpectedToSendInteger = [[NSString stringWithFormat:@"%lld",totalBytesExpectedToSend] integerValue];
//            CGFloat progress = totalByteSentInteger * 1.f / totalBytesExpectedToSendInteger;
//            if (progressBlock){
//                progressBlock(progress);
//            }
//        }
//    };
//
//    OSSTask * putTask = [[AliOSSManager sharedOssManager].oSSClient putObject:put];
//
//    [putTask continueWithBlock:^id(OSSTask *task) {
//        if (!task.error) {
//
//        } else {
//            NSLog(@"upload object failed, error: %@" , task.error);
//        }
//        return nil;
//    }];
//
//    // 可以等待任务完成
//    [putTask waitUntilFinished];
//
//    if (block){
//        block([NSString stringWithFormat:@"%@",put.objectKey]);
//    }
//}
//
//
//
//
//
//
//
//
//
//
//
//
//
//-(NSString *)getFileNameWithType:(ImageUsingType)type{
//    NSString *fileUrl = @"";
//    if (type == ImageUsingTypeBanner){
//        fileUrl = @"Banner";
//    } else if (type == ImageUsingTypeUser){
//        fileUrl = @"User/Avatar";
//    } else if (type == ImageUsingTypeUserShow){
//        fileUrl = @"User/Show";
//    } else if (type == ImageUsingTypeObO){
//        fileUrl = @"Live/OneByOne";
//    } else if (type == ImageUsingTypeLive){
//        fileUrl = @"Live/Live";
//    } else if (type == ImageUsingTypeGift){
//        fileUrl = @"Live/Gift";
//    } else if (type == ImageUsingTypeActivity){
//        fileUrl = @"Activity";
//    } else if (type == ImageUsingTypeShare){
//        fileUrl = @"Share";
//    } else if(type == ImageUsingTypeLaungch){
//        fileUrl = @"Laungch";
//    }
//    NSString *dateStr = [NSDate getOSSFileURL];
//    fileUrl = [fileUrl stringByAppendingString:[NSString stringWithFormat:@"/%@",dateStr]];
//    return fileUrl;
//}
//
//#pragma mark 上传我的相册
//-(void)uploadFileWithImgArray:(NSArray *)imgArr successBlock:(void(^)(BOOL isSuccessed,NSArray *imgArr))block{
//    NSMutableArray<OSSSingleFileModel> *ossFileMutableArr = [NSMutableArray<OSSSingleFileModel> array];
//    for (int i = 0 ; i < imgArr.count;i++){
//        OSSSingleFileModel *ossSingleModel = [[OSSSingleFileModel alloc]init];
//        ossSingleModel.objcImg = [imgArr objectAtIndex:i];
//
//        NSInteger x = arc4random() % 1000;
//        ossSingleModel.objcName = [NSString stringWithFormat:@"%@%@%li.png",[self getFileNameWithType:ImageUsingTypeUserShow],[NSDate getCurrentTimeWithFileName],(long)x];
//        [ossFileMutableArr addObject:ossSingleModel];
//    }
//    __weak typeof(self)weakSelf = self;
//    [[AliOSSManager sharedOssManager] uploadFileWithImgArr:ossFileMutableArr uploadType:ImageUsingTypeUserShow compressionRatio:.8f block:^(NSArray *fileUrlArr) {
//        if (!weakSelf){
//            return ;
//        }
//        __strong typeof(weakSelf)strongSelf = weakSelf;
//        [strongSelf sendRequestToUploadMyImgs:fileUrlArr successBlock:^(BOOL successed) {
//            if (block){
//                block(successed,fileUrlArr);
//            }
//        }];
//    }];
//}
//
//-(void)sendRequestToUploadMyImgs:(NSArray *)imgs successBlock:(void(^)(BOOL successed))block{
//    __weak typeof(self)weakSelf = self;
//
//    NSString *imgsStr = @"";
//    for (int i = 0 ; i < imgs.count;i++){
//        NSString *singleImg = [imgs objectAtIndex:i];
//        if (i == imgs.count - 1){
//            imgsStr = [imgsStr stringByAppendingString:[NSString stringWithFormat:@"%@",singleImg]];
//        } else {
//            imgsStr = [imgsStr stringByAppendingString:[NSString stringWithFormat:@"%@,",singleImg]];
//        }
//    }
//
//    NSDictionary *params = @{@"imgs":imgsStr};
//    [[NetworkAdapter sharedAdapter] fetchWithPath:@"center_uploadImg" requestParams:params responseObjectClass:nil succeededBlock:^(BOOL isSucceeded, id responseObject, NSError *error) {
//        if (!weakSelf){
//            return ;
//        }
//        if (isSucceeded){
//            block(isSucceeded);
//        }
//        [StatusBarManager statusBarHidenWithText:@"【图片相册】上传成功"];
//    }];
//}

@end
